<template>
  <div class="config-manager">
    <h2>图表配置管理</h2>

    <el-table :data="configs" style="width: 100%">
      <el-table-column prop="chartId" label="图表ID" width="180" />
      <el-table-column prop="chartName" label="图表名称" width="180" />
      <el-table-column prop="chartType" label="图表类型" width="120" />
      <el-table-column prop="displayType" label="显示类型" width="120" />
      <el-table-column prop="dataSource" label="数据源" />
      <el-table-column label="操作" width="120">
        <template #default="scope">
          <el-button link type="primary" @click="testConfig(scope.row)">测试</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 测试结果对话框 -->
    <el-dialog v-model="testDialogVisible" title="配置测试结果">
      <div v-if="testResult">
        <p><strong>SQL:</strong> {{ testResult.sql }}</p>
        <p><strong>数据条数:</strong> {{ testResult.dataCount }}</p>
        <el-table :data="testResult.data" style="width: 100%">
          <el-table-column
              v-for="column in testResult.columns"
              :key="column"
              :prop="column"
              :label="column"
          />
        </el-table>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { biApi } from '@/api/bi.js'

const configs = ref([])
const testDialogVisible = ref(false)
const testResult = ref(null)

const loadConfigs = async () => {
  try {
    const response = await biApi.getConfigs()
    if (response.data.success) {
      configs.value = response.data.data
    }
  } catch (error) {
    console.error('加载配置失败:', error)
  }
}

const testConfig = async (config) => {
  try {
    const response = await biApi.getData(config.chartId, {})
    if (response.data.success) {
      debugger
      testResult.value = {
        sql: 'SQL预览功能待实现',
        dataCount: Array.isArray(response.data.data) ? response.data.data.length : 1,
        data: Array.isArray(response.data.data) ? response.data.data : [response.data.data],
        columns: Array.isArray(response.data.data) && response.data.data.length > 0 ?
            Object.keys(response.data.data[0]) : []
      }
      testDialogVisible.value = true
    }
  } catch (error) {
    console.error('测试配置失败:', error)
  }
}

onMounted(() => {
  loadConfigs()
})
</script>